module.exports = app => {
  const express = require('express')
  const Category = require('../../models/Category')
  const Merchandise = require('../../models/Merchandise')
  const Buyer = require('../../models/Buyer')
  const jwt = require('jsonwebtoken')
  const Shopcar = require('../../models/Shopcar')
  const Order = require('../../models/Order')
  const Comment = require('../../models/Comment')

  // 获取父级分类列表
  app.get('/web/api/parentCategories', async (req, res) => {
    //.populate 将关联字段的全部信息获取出来
    var items = await Category.find({parent: {$exists:false}})
    items.unshift({
      name: '首页'
    })
    res.send(items)
  })
  // 查询子类
  app.get('/web/api/childCategories/:id', async (req, res) => {
    // 父级分类id & 查询参数
    var parentId, query
    // 父级分类名
    var item = await Category.findById(req.params.id)
    var name = item.name
    
    // console.log(req.params.name);
    // 通过名称查询父级分类 id
    await Category.find({ name: name }).then(data => {
      if (data.length) {
        parentId = data[0]._id
      }
      query = {
        parent: parentId
      }
    })
    await Category
      .find(query).populate('parent')
      .exec((err, data) => {
        err && res.send({ code: 0, msg: err.errmsg })
        res.send({ code: 1, data })
      })
  })
  app.get('/web/api/allgoods', async (req, res) => {
    var items = await Merchandise.find()
    res.send(items)
  })
  // 分类下的物品
  app.get('/web/api/categorygoods/:id', async (req, res) => {
    var items = await Merchandise.find({'categories.parent': req.params.id})
    res.send(items)
  })
  // 查询分类下 子类的物品
  app.get('/web/api/categorygoodsChild/:id', async (req, res) => {
    var items = await Merchandise.find({'categories.child': req.params.id})
    res.send(items)
  })
  // 搜索物品
  app.get('/web/api/keywordsGoods/:keywords', async (req, res) => {
    let items = await Merchandise.find({"title": {$regex:req.params.keywords,$options:'i'}})
    res.send(items)
  })
  app.get('/web/api/goods/:id', async (req, res) => {
    var items = await Merchandise.findById(req.params.id)
    let vaild = await Comment.findOne({merchandise: req.params.id}).populate('detail.buyer')
    console.log(vaild, 'bbbbbbbbbbb');
    res.send({
      detail: items,
      comment: vaild ? vaild.detail : []
    })
  })

  // 订单详情


  // 注册用户
  app.post('/web/api/regist', async (req,res) => {
    const { username } = req.body
    var valid = await Buyer.findOne({username})
    if (!valid) {
      var model = await Buyer.create(req.body)
      res.send(model)
    } else {
      return res.status(422).send({
        message: '用户已被注册'
      })
    }
  })
  // 登录验证
  app.post('/web/api/login', async (req,res) => {
    const { username, password } = req.body
    const user = await Buyer.findOne({username}).select('+password')
    if(!user) {
      return res.status(422).send({
        message: '用户不存在'
      })
    }
    const isValid = require('bcryptjs').compareSync(password, user.password)
    if(!isValid) {
      return res.status(422).send({
        message: '密码错误'
      })
    }
    // 返回token
    const token =  jwt.sign({ _id: user._id }, app.get('secret'))
    res.send(token)
  })
  // 用户中间件
  async function auto (req, res ,next) {
    const token = String(req.headers.authorization || '').split(' ').pop()
    if (!token) {
      return res.status(401).send({
        message: '请先登录'
      })
    }
    const { _id } = jwt.verify(token, req.app.get('secret'))    
    req.buyer = await Buyer.findById(_id)
    if (!req.buyer) {
      return res.status(401).send({
        message: '请先登录'
      })
    }
    next()
  }
  app.get('/web/api/getuser',auto , async (req,res) => {
    res.send(req.buyer)
  })
  // 上传图片接口
  const multer = require('multer')
  const fs = require('fs')
  const path = require('path')
  const upload = multer({ dest: __dirname + '/../../uploads'})
  // 单图上传
  app.post('/web/api/upload', upload.single('avatar'), function (req, res, next) {
    const file = req.file
    let oldname = file.path //获取path: 'public\\upload\\0f625978d5d1a783b12e149718f8b634',
    let newname = file.path + path.parse(file.originalname).ext //.jpg
    fs.renameSync(oldname, newname)//将老的文件名改成新的有后缀的文件 #同步写法
    file.url = 'http://localhost:3001/uploads/'+file.filename+path.parse(file.originalname).ext
    res.send(file)
  })

  // 修改buyer的收货地址
  app.put('/web/api/updateaddress',auto , async (req, res) => {
    // const token = String(req.params.id || '')
    // const { _id } = jwt.verify(token, req.app.get('secret'))   
    user = await Buyer.findById(req.buyer._id, (err,buyer) => {
      // 1新增
      if (!req.body._id) {
        // console.log('ok');
        buyer.addresses.push(req.body)
      }
      // 2修改
      if (req.body.isDefault) {
        // 1）默认地址为真
        for(let i=0; i<buyer.addresses.length; i++){
          buyer.addresses[i].isDefault = false
        }
        for(let i=0; i<buyer.addresses.length; i++){
          if (String(buyer.addresses[i]._id) === String(req.body._id)) {
            buyer.addresses[i] = req.body
          }
        }
      } else {
        // 2）默认地址为false 
        for(let i=0; i<buyer.addresses.length; i++){
          if (String(buyer.addresses[i]._id) === String(req.body._id)) {
            buyer.addresses[i] = req.body
          }
        }
      }
      // console.log(buyer)
      buyer.save()
      res.send('ok')
    })
  })
  // 用户支付密码 
  app.put('/web/api/payword', auto, async (req,res) => {
    req.buyer.payword = req.body.payword
    // console.log(req.buyer);
    var model = await Buyer.findByIdAndUpdate(req.buyer._id, req.buyer)
    // console.log(model)
    res.send('ok')
  })
  // 修改昵称
  app.put('/web/api/buyername', auto, async (req,res) => {
    req.buyer.buyername = req.body.buyername
    // console.log(req.buyer);
    var model = await Buyer.findByIdAndUpdate(req.buyer._id, req.buyer)
    // console.log(model)
    res.send('ok')
  })
  // 修改密码
  app.put('/web/api/password', auto, async (req,res) => {
    req.buyer.password = req.body.password
    var model = await Buyer.findByIdAndUpdate(req.buyer._id, {password: req.body.password})
    res.send('ok')
  })

  /* 
  购物车
  */
  app.post('/web/api/addtoshopcar',auto ,async (req,res)=>{
    // console.log(req.buyer._id);
    req.body.buyer = String(req.buyer._id)
    var model = await Shopcar.create(req.body)
    res.send(model)
  })
  app.get('/web/api/getshopcar',auto, async (req,res) => {
    var model = await Shopcar.find({ buyer: req.buyer._id}).populate('merchandise')
    res.send(model)
  })
  // 购物车删除
  app.post('/web/api/deleteshopcar', auto, async (req,res) => {
    await Shopcar.deleteMany({_id:{ $in: req.body }})
    res.send('ok')
  })

   /* 
  订单
  */
  app.post('/web/api/order/:pw', auto, async (req,res) =>{
    // 插入id
    req.body.buyer = req.buyer._id
    // 判断支付密码
    if (req.buyer.payword === req.params.pw) {
      var model = await Order.create(req.body)
      res.send({
        model,
        code: 1
      })
    } else {
      res.send({
        code: 0,
        message: '密码错误'
      })
    }
  })
  app.get('/web/api/order', auto, async (req,res) => {
    console.log(req.buyer._id);
    var model = await Order.find({buyer:req.buyer._id})
    res.send(model)
  })
  // 获取单个订单
  app.get('/web/api/orderdetail/:id', auto, async (req,res) => {
    let model = await Order.find({_id: req.params.id})
    res.send(model)
  })
  // 根据订单状态获取
  app.get('/web/api/orderstate/:orderstate', auto, async (req, res) => {
    let model = await Order.find({orderstate: req.params.orderstate, buyer:req.buyer._id})
    res.send(model)
  })
  // 确认收货
  app.get('/web/api/confirmorder/:id', auto, async (req, res) => {
    let model = await Order.find({_id: req.params.id})
    model[0].orderstate = '待评价'
    let m = await Order.findByIdAndUpdate(req.params.id, model[0])
    res.send(m)
  })

  // 评价
  app.post('/web/api/comment', auto, async (req, res) => {
    req.body.comment.forEach(async (item) => {
      let one = {
        isGood: item.isGood,
        buyer: req.buyer._id,
        comment: item.comment,
        img: item.img,
        color: item.color,
        size: item.size,
        star: item.star
      }
      let vaild = await Comment.find({merchandise: item.merchandise})
      console.log(vaild , item.merchandise, 'item.merchandise');
      // return
      if (vaild.length > 0) {
        vaild[0].detail.push(one)
        let res = await Comment.findByIdAndUpdate(vaild[0]._id, vaild[0])
        console.log('插入评论成功');
      } else {
        let m = {
          merchandise: item.merchandise,
          detail: [one]
        }
        console.log(m);
        let model = await Comment.create(m)
        console.log('创建成功评论');
      }
    })
    let model = await Order.find({_id: req.body.orderId})
    model[0].orderstate = '已完成'
    let m = await Order.findByIdAndUpdate(req.body.orderId, model[0])
    res.send(m)
  })
}
